package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.DishMapper;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.result.PageResult;
import com.sky.service.AddressBookService;
import com.sky.service.OrderService;
import com.sky.service.ShoppingCartService;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private AddressBookService addressBookService;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private DishMapper dishMapper;

    @Override
    @Transactional
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {
        //异常情况的处理（收货地址为空、超出配送范围、购物车为空）
        List<ShoppingCart> shoppingCartList = shoppingCartService.getByUserId(BaseContext.getCurrentId());
        if (shoppingCartList == null && shoppingCartList.size() == 0 ) {
            throw new ShoppingCartBusinessException("购物车为空");
        }
        AddressBook addressBook = addressBookService.getById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null) {
            throw new ShoppingCartBusinessException("地址不存在");
        }
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getDetail());
        orders.setConsignee(addressBook.getConsignee());
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setUserId(BaseContext.getCurrentId());
        orders.setPayStatus(Orders.UN_PAID);
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCancelTime(LocalDateTime.now());
        orders.setConsignee(addressBook.getConsignee());
        orders.setDeliveryTime(LocalDateTime.now());

        orderMapper.submit(orders);
        //模拟数据
        Integer status = Orders.TO_BE_CONFIRMED;
        Integer payStatus = Orders.PAID;
        orders.setStatus(status);
        orders.setPayStatus(payStatus);
        orderMapper.update(orders);
        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart shoppingCart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart, orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetailList.add(orderDetail);
        }
        orderDetailMapper.insetBatch(orderDetailList);
        shoppingCartService.delAllByUserId();
        OrderSubmitVO orderSubmitVO;
        orderSubmitVO = OrderSubmitVO.builder()
                .id(orders.getId())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .orderTime(orders.getOrderTime())
                .build();

        return orderSubmitVO;
    }

    @Override
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) {

        return new OrderPaymentVO();
    }

    @Override
    public PageResult page(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        Page<OrderVO> ordersPage = orderMapper.page(ordersPageQueryDTO);
        List<OrderVO> resultList = ordersPage.getResult();
        for (OrderVO orderVO : resultList) {
            List<OrderDetail> list = orderDetailMapper.getListByOrderId(orderVO.getId());
            orderVO.setOrderDetailList(list);
            //创建一个空的字符串
            String name = "";
            for (OrderDetail orderDetail : list) {
                name += orderDetail.getName()+"";
            }
            orderVO.setOrderDishes(name);
        }
        return new PageResult(ordersPage.getTotal(),ordersPage.getResult());
    }

    @Override
    public OrderVO orderDetailId(Long id) {
        OrderVO orderVO = new OrderVO();
        //根据id查询订单数据
        Orders orders = new Orders();
        orders.setUserId(BaseContext.getCurrentId());
        orders = orderMapper.getOrdersById(id);
        BeanUtils.copyProperties(orders,orderVO);

        //根据订单id查询订单详情
        List<OrderDetail> orderDetails = orderDetailMapper.getListByOrderId(orders.getId());
        if (orderDetails!=null && orderDetails.size()>0){
            orderVO.setOrderDetailList(orderDetails);
        }
        return orderVO;
    }

    @Override
    public void update(Long id) {
        Orders orders = orderMapper.getOrdersById(id);
        orders.setUserId(BaseContext.getCurrentId());
        orders.setStatus(Orders.CANCELLED);
        orderMapper.updateById(orders);
    }

    @Override
    public void repetition(Long id) {
        //根据id查询订单数据
        Orders orders = orderMapper.getOrdersById(id);
        orders.setUserId(BaseContext.getCurrentId());
        List<OrderDetail> orderDetails = orderDetailMapper.getListByOrderId(orders.getId());
        List<ShoppingCart> shoppingCarts = new ArrayList<>();
        ShoppingCart shoppingCart = new ShoppingCart();
        //把数据放到购物车
        for (OrderDetail orderDetail : orderDetails) {
            //
            shoppingCart.setUserId(BaseContext.getCurrentId());
            BeanUtils.copyProperties(orderDetail,shoppingCart);
            shoppingCart.setCreateTime(LocalDateTime.now());
            //
            shoppingCartMapper.add(shoppingCart);
        }
    }

    @Override
    public OrderVO details(Long id) {
        OrderVO orderVO = new OrderVO();
        //根据id查询订单数据
        Orders orders = orderMapper.getOrdersById(id);
        BeanUtils.copyProperties(orders,orderVO);
        List<OrderDetail> orderDetails = orderDetailMapper.getListByOrderId(orders.getId());
        if(orderDetails!=null && orderDetails.size()>0){
            orderVO.setOrderDetailList(orderDetails);
        }
        return orderVO;
    }

    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        Orders orders = orderMapper.getOrdersById(ordersConfirmDTO.getId());
        orders.setUserId(BaseContext.getCurrentId());
        orders.setStatus(Orders.CONFIRMED);
        orderMapper.updateById(orders);

    }

    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        Orders orders = orderMapper.getOrdersById(ordersRejectionDTO.getId());
        orders.setUserId(BaseContext.getCurrentId());
        orders.setStatus(Orders.CANCELLED);
        orders.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        orderMapper.updateById(orders);
    }

    @Override
    public void delivery(Integer id) {
        Orders orders = orderMapper.getOrdersByIId(id);
        orders.setUserId(BaseContext.getCurrentId());
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
        orderMapper.updateById(orders);
    }

    @Override
    public void complete(Integer id) {
        Orders orders = orderMapper.getOrdersByIId(id);
        orders.setUserId(BaseContext.getCurrentId());
        orders.setStatus(Orders.COMPLETED);
        orderMapper.updateById(orders);
    }

    @Override
    public OrderStatisticsVO statistics() {
        OrderStatisticsVO statisticsVO = new OrderStatisticsVO();
        //查询待接单数量
        List<Orders> orders = orderMapper.getDJD(Orders.TO_BE_CONFIRMED);
        statisticsVO.setToBeConfirmed(orders.size());
        //查询待派送数量
        List<Orders> orders2 = orderMapper.getDJD(Orders.CONFIRMED);
        statisticsVO.setConfirmed(orders2.size());
        //查询配送中数量
        List<Orders> orders3 = orderMapper.getDJD(Orders.DELIVERY_IN_PROGRESS);
        statisticsVO.setDeliveryInProgress(orders3.size());
        return statisticsVO;
    }
}
